/**
 * 格式化时间戳为标准日期时间字符串
 * @param timestamp - 时间戳（秒级或毫秒级）或日期字符串
 * @returns 格式化后的日期时间字符串或错误提示
 */
export const formatTimestamp = (timestamp: number | string | Date): string => {
  // 检查无效输入
  if (timestamp === undefined || timestamp === null) return "无时间数据";

  try {
    let date: Date;

    // 根据输入类型处理
    if (timestamp instanceof Date) {
      date = timestamp;
    } else if (typeof timestamp === "string") {
      // 尝试直接解析日期字符串
      date = new Date(timestamp);
      // 如果解析失败，尝试作为时间戳处理
      if (isNaN(date.getTime())) {
        const numTimestamp = Number(timestamp);
        date = new Date(numTimestamp > 9999999999 ? numTimestamp : numTimestamp * 1000);
      }
    } else {
      // number类型
      date = new Date(timestamp > 9999999999 ? timestamp : timestamp * 1000);
    }

    // 验证日期有效性
    if (isNaN(date.getTime())) return "时间格式错误";

    // 获取日期时间组件
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");

    // 组合成目标格式
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (e) {
    return "时间解析失败";
  }
};

/**
 * 格式化日期为YYYY-MM-DD HH:mm:ss字符串
 * @param date 要格式化的日期对象
 * @param isStartOfDay 是否为开始时间（设置为零点）
 * @returns 格式化后的日期字符串
 */
export const formatDateTime = (date: Date, isStartOfDay: boolean = false): string => {
  const d = new Date(date);
  if (isStartOfDay) d.setHours(0, 0, 0, 0);

  const pad = (num: number) => String(num).padStart(2, "0");

  return [
    `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`,
    isStartOfDay ? "00:00:00" : `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  ].join(" ");
};
